<?php
namespace Backend\Controllers;

use Models\App;
use Models\AppUser;
use Models\User;

class AppController extends BaseController
{
    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page');
        $apps = App::find('del=0');
        $paginator = new \Phalcon\Paginator\Adapter\Model(array(
            "data" => $apps,
            "limit" => 10,
            "page" => $currentPage,
        ));
        $this->view->page = $paginator->getPaginate();

    }

    public function infoAction($id)
    {
        $app = App::findFirstByid(intval($id));
        if (!$app) $this->flash->warning("不存在此应用");
        $this->view->setVar("app", $app);
    }

    public function buyAction($id)
    {
        $Cuser = $this->Cuser;
        $user = User::findFirstByuid($Cuser->uid);
        $Csum = $user->sum;
        $app = App::findFirstByid(intval($id));
        $price = $app->price;
        if ($Csum >= $price) {
            $user->sum = $Csum - $price;
            $where = "uid='" . $Cuser->uid . "'AND appid = '" . $id . "' AND end>'" . date("Y-m-d H:i:s", strtotime("now")) . "'";
            $Y = AppUser::findFirst($where);
            if (!$Y) {
                if ($user->save()) {
                    $appuser = new AppUser();
                    $appuser->uid = $Cuser->uid;
                    $appuser->appid = intval($id);
                    $appuser->start = date("Y-m-d H:i:s", strtotime("now"));
                    $appuser->end = date("Y-m-d H:i:s", strtotime('+90 days'));
                    $appuser->price=$price;
                    $appuser->del=0;
                    $appuser->save();
                    $status = 'success';
                } else {
                    $status = 'error';
                };
            } else {

                $status = 'yjgm';
            }
        } else {

            $status = 'jfbg';

        }
        echo json_encode(array('status' => $status, 'error_msg' => ''));

    }

    public function myappAction()
    {

    }
}